package com.vueblog.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vueblog.po.Blog;
import com.vueblog.service.BlogService;
import com.vueblog.vo.SimpleBlog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class BlogController {

    private final int pageSize=5;
    @Autowired
    private BlogService blogService;

    @GetMapping("/searchBlogList")
    public Object searchBlogList(Blog blog,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        JSONObject jsonObject = new JSONObject();
        String orderBy = "update_time desc";
        PageHelper.startPage(pageNum,pageSize,orderBy);
        List<SimpleBlog> blogs = blogService.findByTitleAndTypeIdAndPublished(blog);
        PageInfo<SimpleBlog> pageInfo = new PageInfo<SimpleBlog>(blogs);
        jsonObject.put("pageInfo",pageInfo);
        return jsonObject;
    }

    @PostMapping("/saveBlog")
    public Object saveBlog(@RequestBody Blog blog){
        JSONObject jsonObject = new JSONObject();
        int i = blogService.saveBlog(blog);
        if (i>0){
            jsonObject.put("status",200);
            jsonObject.put("msg","保存成功");
        }else {
            jsonObject.put("status",500);
            jsonObject.put("msg","保存失败，发生未知错误");
        }
        return jsonObject;
    }

    @GetMapping("/getDetailBlog")
    public Object getDetailBlog(@RequestParam int id){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("blog",blogService.findDetailBlogById(id));
        return jsonObject;
    }

    @PostMapping("/updateBlog")
    public Object updateBlog(@RequestBody Blog blog){
        JSONObject jsonObject = new JSONObject();
        int i = blogService.updateBlog(blog);
        if (i>0){
            jsonObject.put("status",200);
            jsonObject.put("msg","更新成功");
        }else {
            jsonObject.put("status",500);
            jsonObject.put("msg","更新失败，发生未知错误");
        };
        return jsonObject;
    }

    @PostMapping("/deleteBlog")
    private Object deleteBlog(@RequestBody Blog blog){
        JSONObject jsonObject = new JSONObject();
        int i = blogService.deleteBlog(blog.getId());
        if (i>0){
            jsonObject.put("status",200);
            jsonObject.put("msg","删除成功");
        }else {
            jsonObject.put("msg","删除失败，发生未知错误");
        }
        return jsonObject;
    }
}
